﻿@inject IHttpService _httpService

@inject ILocalStorageService _localStorage

@inject IPopupService PopupService


@inject NavigationManager NavigationManager

<CnGalWebSite.Shared.MasaComponent.Shared.Cards.TitleTip Title="编辑个人主页"/>

<AutoSaveTip TItem="EditUserMainPageViewModel" Item="Model" DataLoaded="DataLoaded" @ref="autoSave" />

<div>
    @if (isReady == false)
    {
        <CnGalWebSite.Components.Progressings.ProgressingCard Page Fill />
    }
    else
    {
        <CnGalWebSite.Components.Containers.MasaTitleContainer Title="编辑个人主页" Icon="@IconType.MainPage.ToIconString()" Outline>
            <CnGalWebSite.Shared.MasaComponent.Shared.Editors.Users.MainPageCard Model="Model" Class="mb-4"/>
            <CnGalWebSite.Shared.MasaComponent.Shared.Editors.Buttons.SubmitButton OnSubmit="OnSubmit" Model="Model" />
        </CnGalWebSite.Components.Containers.MasaTitleContainer>
    }

</div>


@code {
    [Parameter]
    public string Id { get; set; }
    public EditUserMainPageViewModel Model { get; set; } = new EditUserMainPageViewModel();
    bool isReady = false;

    [CascadingParameter]
    public ErrorHandler ErrorHandler { get; set; }

    AutoSaveTip<EditUserMainPageViewModel> autoSave { get; set; }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            try
            {
                Model = await _httpService.GetAsync<EditUserMainPageViewModel>("api/space/editmainpage");
                isReady = true;
                StateHasChanged();
            }
            catch (Exception ex)
            {
                await ErrorHandler.ProcessError(ex, "获取编辑用户主页失败");
            }
        }
    }

    private async Task OnSubmit()
    {
        //上传
        try
        {
            var obj = await _httpService.PostAsync<EditUserMainPageViewModel, Result>("api/space/editmainpage", Model);

            //判断结果
            if (obj.Successful == false)
            {
                await PopupService.ToastErrorAsync("保存用户主页失败", obj.Error);
            }
            else
            {
                autoSave.Clean();

                await PopupService.ToastSuccessAsync("保存成功", "保存用户主页成功，等待审核通过");
                NavigationManager.NavigateTo("/space/index/" + Model.Id);
            }
        }
        catch (Exception ex)
        {
            await ErrorHandler.ProcessError(ex, "保存用户主页失败");
        }
    }


    private void DataLoaded(EditUserMainPageViewModel model)
    {
        isReady = false;
        StateHasChanged();
        Model = model;
        isReady = true;
        StateHasChanged();
        
    }

}
